<template>
  <div class="app-container">
    <el-form :model="queryParams" :inline="true">
      <el-form-item prop="title" :label="$t('query.deviceImei')">
        <el-autocomplete v-model.trim="queryParams.deviceId"
                         :placeholder="$t('query.placeholder.deviceImei')"
                         class="inline-input"
                         :fetch-suggestions="queryDevice"
                         :trigger-on-focus="false"
                         style="width: 350px;"
                         :maxlength="80"
                         size="small">
        </el-autocomplete>
      </el-form-item>

      <el-form-item :label="$t('query.dateRange')">
        <el-date-picker
          v-model="dateRange"
          size="small"
          type="datetimerange"
          range-separator="-"
          :start-placeholder="$t('query.placeholder.dateRange.start')"
          :end-placeholder="$t('query.placeholder.dateRange.end')"
          :clearable="false"
        ></el-date-picker>
      </el-form-item>

      <el-form-item :label="$t('query.event.eventType')">
        <el-select
          :placeholder="$t('query.event.placeholder.eventType')"
          :clearable="false"
          v-model="queryTypes"
          multiple
          collapse-tags
          style="width:270px"
          size="small">
          <el-option
            v-for="dict in eventTypeOption"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" v-hasPermi="['data:event:query']" v-loading="loading" @click="handleQuery">
          {{$t('query.search')}}
        </el-button>
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          v-hasPermi="['data:event:export']"
          @click="handleExport">
          {{$t('query.export')}}
        </el-button>
      </el-form-item>

    </el-form>

    <el-table border v-loading="loading" :data="list" ref="table" :empty-text="$t('query.noData')">
      <el-table-column :label="$t('query.deviceCode')" align="center" prop="deviceId" width="250"></el-table-column>
      <el-table-column :label="$t('query.recordTime')" align="center" prop="recordTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.recordTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('query.deviceTime')" align="center" prop="deviceTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deviceTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('query.event.eventType')" align="center" prop="type" width="180">
        <template slot-scope="scope">
          <span v-text="scope.row.type"></span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('query.event.eventDescription')" align="center" width="260">
        <template slot-scope="scope">
          <span v-text="eventTypeFormat(scope.row.type)"></span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('query.event.gps')" align="center" prop="gps" width="180">
        <template slot-scope="scope">
          <el-link type="primary" v-if="scope.row.gps != null" @click="clickGps(scope.row.gps)">
            {{$t('query.event.gpsInfo')}}</el-link>
        </template>
      </el-table-column>

      <el-table-column :label="$t('query.event.connect')" align="center" prop="connect" width="180">
        <template slot-scope="scope">
          <el-link type="primary" v-if="scope.row.connect != null" @click="clickConnect(scope.row.connect)">
            {{$t('query.event.connectInfo')}}</el-link>
        </template>
      </el-table-column>
      <el-table-column :label="$t('query.event.disconnect')" align="center" prop="disconnect" width="180">
        <template slot-scope="scope">
          <el-link type="primary" v-if="scope.row.disconnect != null" @click="clickDisconnect(scope.row.disconnect)">
            {{$t('query.event.disconnectInfo')}}</el-link>
        </template>
      </el-table-column>
      <el-table-column :label="$t('query.event.upgrade')" align="center" prop="upgrade" width="180" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.upgrade != null ? JSON.stringify(scope.row.upgrade): '' }}
        </template>
<!--        <template slot-scope="scope">-->
<!--          <el-link type="primary" v-if="scope.row.upgrade != null" @click="clickUpgrade(scope.row.upgrade)">-->
<!--            {{$t('query.event.upgradeInfo')}}</el-link>-->
<!--        </template>-->
      </el-table-column>

      <el-table-column :label="$t('query.event.attach')" align="center" prop="attach" width="265"
                       show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.attach != null ? JSON.stringify(scope.row.attach): '' }}
        </template>
      </el-table-column>

    </el-table>
    <el-row type="flex" justify="end">
        <el-col :span="3.5">
          <el-button-group>
            <el-button type="cyan" icon="el-icon-arrow-left" size="mini" :disabled="pageItems.length === 0"
                       @click="handlePrev">{{$t('query.prePage')}}
            </el-button>
            <el-button type="cyan" size="mini" :disabled="list.length < 10" @click="handleNext">
              {{$t('query.nextPage')}}<i class="el-icon-arrow-right el-icon--right"></i></el-button>
          </el-button-group>
        </el-col>
      </el-row>

    <gps ref="gps"></gps>
    <connect ref="connect"></connect>
    <disconnect ref="disconnect"></disconnect>
    <upgrade ref="upgrade"></upgrade>
  </div>
</template>

<script>
  import {event,EVENT_TYPES} from "@/api/query/data"
  import {getToken} from "@/utils/auth";
  import {queryDeviceIdAsync} from '@/api/query/device';
  import Connect from './moudle/connect'
  import Disconnect from './moudle/disconnect'
  import Upgrade from './moudle/upgrade'
  import Gps from './moudle/gps'

  export default {
    name: "Event",
    components: { Gps, Upgrade, Disconnect, Connect },
    data() {
      return {
        queryTypes: [],
        queryParams: {
          table: "keeway-event",
          deviceId: null,
          types: [],
          from: new Date(),
          to: new Date()
        },
        dateRange: [new Date(new Date().getTime() - 3600 * 1000 * 24 * 7), new Date(new Date().getTime() + 3600 * 1000 * 24)],
        loading: false,

        list: [],
        pageItems: [],
        source: null,

        eventTypeOption: EVENT_TYPES
      }
    },

    methods: {
      /** 搜索按钮操作 */
      handleQuery() {
        if (!this.validInput()) {
          return;
        }

        this.queryParams.from = this.dateRange[0].getTime();
        this.queryParams.to = this.dateRange[1].getTime();
        this.pageItems = [];
        this.loading = true;
        this.getList(this.queryParams);
      },

      eventTypeFormat(type) {
        for (let i = 0; i < this.eventTypeOption.length; i++) {
          if (this.eventTypeOption[i].value === type) {
            return this.eventTypeOption[i].label
            break;
          }
        }
        return type
      },

      handlePrev() {
        if (!this.validInput()) {
          return;
        }
        this.loading = true;
        this.queryParams.to = this.pageItems.pop();
        this.getList(this.queryParams);
      },

      handleNext() {
        if (!this.validInput()) {
          return;
        }
        this.loading = true;
        this.pageItems.push(this.list[0].deviceTime)
        this.queryParams.to = this.list[this.list.length - 1].deviceTime - 1
        this.getList(this.queryParams);
      },

      getList(queryParams) {
        queryParams.types = this.queryTypes.join(",");
        event(queryParams).then(rsp => {
          this.list = rsp.data;
          this.loading = false;
        })
      },

      queryDevice(suffix, cb) {
        let form = {deviceId: suffix, source: this.source}
        queryDeviceIdAsync(form, cb);
      },

      clickGps(data) {
        this.$refs.gps.init(data);
      },
      clickConnect(data) {
        this.$refs.connect.init(data);
      },
      clickDisconnect(data) {
        this.$refs.disconnect.init(data);
      },
      clickUpgrade(data) {
        this.$refs.upgrade.init(data);
      },

      handleExport() {
        if (!this.validInput()) {
          return;
        }

        let table = this.$refs.table;
        let cols = table.$children.filter(it => {
          return it.prop !== null && it.prop !== undefined && it.label !== null && it.label !== undefined;
        });

        let props = cols.map(it => {
          return it.prop;
        }).join(",");

        let labels = cols.map(it => {
          return it.label;
        }).join(",")

        let path = "/query/data/export";

        const params = {
          table: this.queryParams.table,
          deviceId: this.queryParams.deviceId,
          from: this.dateRange[0].getTime(),
          to: this.dateRange[1].getTime(),
          Authorization: 'Bearer ' + getToken(),
          types: this.queryParams.types,
          props: props,
          labels: labels
        }

        const baseURL = process.env.VUE_APP_BASE_API

        const qs = Object.keys(params)
          .map(key => `${key}=${params[key]}`)
          .join('&');

        window.location.href = baseURL + path + "?" + qs;
      },

      validInput() {
        if (this.queryParams.deviceId === "" || this.queryParams.deviceId === undefined
          || this.queryParams.deviceId === null) {
          this.$message({
            showClose: true,
            duration: 1000,
            message: this.$t('query.inputDeviceNumber'),
            type: 'warning'
          });
          return false;
        }

        if (this.dateRange.length !== 2) {
          this.$message({
            showClose: true,
            duration: 1000,
            message: this.$t('query.selectTimeRange'),
            type: 'warning'
          });
          return false;
        }
        return true;
      },
    }
  };
</script>

<style scoped>

</style>
